package com.gingko.duominuo.ui.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import com.gingko.duominuo.data.datastore.DataStoreHelper
import com.gingko.duominuo.databinding.FragmentUserBinding
import com.gingko.duominuo.ui.activity.LoginActivity
import com.gingko.duominuo.ui.activity.WorkOrderRecordActivity
import com.gingko.duominuo.utils.singleClick
import com.gingko.duominuo.viewmodel.UserViewModel
import kotlinx.coroutines.runBlocking

class UserFragment : BaseFragment() {

    private val mViewModel by activityViewModels<UserViewModel>()
    private val mViewBinding: FragmentUserBinding by lazy { FragmentUserBinding.inflate(layoutInflater) }

    companion object {
        @JvmStatic
        fun newInstance() = UserFragment()
    }

    override fun getContentView(inflater: LayoutInflater, container: ViewGroup?): View {
        return mViewBinding.root
    }

    override fun getViewModel(): UserViewModel {
        return mViewModel
    }

    override fun initView(view: View, savedInstanceState: Bundle?) {
        runBlocking {
            mViewBinding.ivKernel.isSelected = DataStoreHelper.isUseX5Kernel()
        }
        mViewBinding.tvWorkOrderHistory.singleClick {
            WorkOrderRecordActivity.start(requireContext())
        }
        mViewBinding.ivKernel.singleClick {
            it.isSelected = !it.isSelected
            runBlocking {
                DataStoreHelper.saveIsUseX5Kernel(it.isSelected)
            }
        }
        mViewBinding.tvLogout.singleClick {
            runBlocking {
                DataStoreHelper.saveIsLogin(false)
            }
            LoginActivity.start(requireActivity())
            requireActivity().finish()
        }
        mViewModel.userInfoLiveData.observe(this) {
            it?.let {
                mViewBinding.tvUserName.text = it.name
                mViewBinding.tvPhoneNumber.text = it.account
            }
        }
        mViewModel.getUserInfoFromDb()
    }
}